﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace AzureDiagMon.Common.Helpers
{
    public static class EnumerableExtensions
    {
        /// <summary>
        /// Flush after every flushItemCount items.
        /// The flush action will be called with flushItemCount sized pages.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <param name="flushItemCount"></param>
        /// <param name="flushAction"></param>
        public static void Flush<T>(this IEnumerable<T> items, int flushItemCount, Action<IEnumerable<T>> flushAction)
        {
            if (items == null)
                throw new ArgumentNullException("items");

            var cnt = 0;
            var page = new T[flushItemCount];

            foreach (var item in items)
            {
                page[cnt] = item;
                if (++cnt == flushItemCount)
                {
                    flushAction(page);
                    cnt = 0;
                }
            }

            if (cnt > 0)
            {
                var lastPage = page.Take(cnt);
                flushAction(lastPage);
            }
        }
    }
}
